<template>
  <m-layout class="farm" title="" color="#fff" gap="0 24" :goBack="false" barBg="unset">
    <!-- 顶部 -->
    <view slot="back">
      <m-image2 :size="[198, 40]" src="../../static/images/pages/farm/farmTop.png" />
    </view>
    <view slot="right" class="flex" @click="Jump('/pages/farm/record/index')">
      <m-icon type="recive" size="40" />
      <text class="fs24 ml-4 text-black">領取記錄</text>
    </view>

    <!-- 主要内容 -->
    <view class="flex-column">
      <!-- 欢迎文字 -->
      <view class="flex mb-20">
        <m-icon type="coin" size="30" />
        <text class="fs22 ml-12">歡迎來到農場，快人一步，解鎖專屬獎勵！</text>
      </view>

      <!-- 累计收获 -->
      <m-block class="totalCount flex fs26 pl-20 jc-center">
        <m-icon type="coin2" size="30" />
        <text class="mlr-12">累計已收穫</text>
        <view class="flex">
          <text>{{ receiveData.receiveCount }}</text>
          <text class="ml-4">果實</text>
        </view>
      </m-block>

      <!-- 农场图片和状态 -->
      <view class="imgBox flex-column jc-center plr-32 pt-300">
        <m-image2 :size="[627, 653]" src="../../static/images/pages/farm/tree.png" />
        <text class="fs21 farmState flex jc-center" :class="[receiveData.state == 1 ? '' : 'text-red']">
          {{ receiveData.state == 1 ? '生產中...' : '已結束' }}
        </text>
      </view>

      <!-- 按钮区域 -->
      <view class="btnBox flex-column mt-20">
        <!-- 下次领取时间 -->
        <view class="flex jc-center fs24 mtb-12 text-white" v-if="receiveData.receiveNext">
          <text>下一次領取:</text>
          <view class="flex">
            <text>{{ receiveData.receiveNext.replace('T', ' ').slice(0, 16) }}</text>
          </view>
        </view>

        <!-- 领取按钮 -->
        <view class="recBtn flex jc-center ai-baseline pt-24" @click="handleUseFeature()">
          <view class="flex" v-if="Number(startTime) > 0">
            <mCountDown color="#fff" :timestamp="startTime" />
          </view>
          <view class="flex text-white" v-else>
            <text v-if="receiveData.receive == 1">領取</text>
          </view>
          <text class="fs26 ml-8 text-white">{{ receiveData.receiveNum }}</text>
          <text class="fs24 text-white">果實</text>
        </view>
      </view>
    </view>

    <!-- 成功弹窗 -->
    <m-dialog title="" :showCancel="false" :isShow="tipsShow" @handleCancel="tipsShow = false"
      @handleConfirm="tipsShow = false">
      <view class="ptb-48 flex-column jc-center ai-center">
        <m-image2 :size="[260, 260]" src="../../static/images/pages/farm/success.png" />
        <text>領取成功</text>
        <view class="flex text-primary fs26 mt-12">
          <text>收穫</text>
          <text>{{ receiveData.receiveNum }}</text>
          <text class="fs24">果實</text>
        </view>
      </view>
    </m-dialog>
  </m-layout>
</template>

<script>
import { mapState } from 'vuex';
import { myFruit, Receive } from '@/api/Activetion.js';
import { creditdetal } from '@/api/Trade.js';
import mCountDown from '@/components/m-countdown/index.vue';
import rewardVideoAdManager from '@/utils/rewardVideoAdManager/index.js';

export default {
  components: {
    mCountDown
  },
  data() {
    return {
      credittype: '41', // 农场收益
      receiveData: {},
      typeid: 1,
      listArr: [],
      pageIndex: 1,
      pageSize: 10,
      pageCount: 1,
      isLoading: false,
      startTime: 0,
      tipsShow: false,
      adCount:0 ,  // 今日已看广告
    };
  },

  onLoad() {
    console.log('农场页面加载');
  },

  onReady() {
    console.log('农场页面准备完成，初始化广告管理器');
    this.initAdManager();
  },

  computed: {
    ...mapState({
      userInfo: (state) => state.user.userinfo,
      coinConfig: (state) => state.general.coinConfig,
      config: (state) => state.general.config,
      timespan: (state) => state.general.timespan
    }),
    // 每日光看广告次数
    config601() {
      return Number(this.config[601] || 10);
    }
  },

  onShow() {
    console.log('农场页面显示');

    // ✅ 页面显示时预加载广告（确保6小时后能快速显示广告）
    rewardVideoAdManager.preload();

    this.reset();
  },

  onUnload() {
    console.log('农场页面卸载，销毁广告管理器');
    rewardVideoAdManager.destroy();
  },

  methods: {
    /**
     * 初始化广告管理器
     */
    initAdManager() {
      console.log('=== 开始初始化广告管理器 ===');

      // 检测环境（与原始代码保持一致）
      const isApp = rewardVideoAdManager.checkEnvironment();

      // 设置回调函数
      rewardVideoAdManager.setCallbacks({
        onAdComplete: (res) => {
          console.log('✅ 广告观看完成回调');
          this.ReceiveFn();
        },
        onAdIncomplete: (res) => {
          console.log('❌ 广告观看未完成回调');
        },
        onH5Fallback: () => {
          console.log('H5环境降级回调');
        },
        onFallback: () => {
          console.log('广告失败降级回调');
          this.ReceiveFn();
        }
      });

      // 如果是App环境，初始化广告（与原始代码保持一致）
      if (isApp) {
        console.log('开始初始化广告...');
        rewardVideoAdManager.init({ userId: this.userInfo.userid });
      } else {
        console.log('非App环境，跳过广告初始化');
      }

      console.log('=== 广告管理器初始化完成 ===');
    },

    /**
     * 用户点击使用功能
     */
    async handleUseFeature() {
      console.log('用户点击领取按钮');

      // 检查是否到领取时间
      if (this.receiveData.receive !== 1) {
        return this.Toast('未到领取时间');
      }

      // 显示确认弹窗
      const confirm = await rewardVideoAdManager.showConfirm(
        '觀看完廣告後可領取果實'
      );

      if (!confirm) {
        console.log('用户取消观看广告');
        return;
      }

      console.log('用户确认观看广告，开始显示广告');

      // 显示广告
      const success = await rewardVideoAdManager.showRewardedVideoAd();

      if (!success) {
        console.log('广告显示失败');
      }
    },

    /**
     * 初始化数据
     */
    reset() {
      console.log('重置页面数据');
      this.pageCount = 1;
      this.pageIndex = 1;
      this.receiveDataFn();
      this.getData();
    },

    /**
     * 获取时间戳
     */
    getTimestamp(timeStr) {
      const timestamp = Math.floor(new Date(timeStr).getTime() / 1000);
      this.startTime = Number(timestamp) - this.timespan;
    },

    /**
     * 领取果实
     */
    async ReceiveFn() {
      console.log('开始领取果实');

      const { success, msg } = await Receive();
      this.Toast(msg);

      if (!success) {
        console.log('领取失败:', msg);
        return;
      }

      console.log('领取成功');
      this.tipsShow = true;
      this.reset();
    },

    /**
     * 获取农场数据
     */
    async receiveDataFn() {
      console.log('获取农场数据');

      const { success, msg, data } = await myFruit();

      if (!success) {
        console.log('获取农场数据失败:', msg);
        return;
      }

      this.receiveData = data;
      this.adCount = Number(data.adCount || 0);
      this.getTimestamp(data.receiveNext);
      console.log('农场数据获取成功:', data);
    },

    /**
     * 获取转让记录列表
     */
    async getData() {
      if (this.pageIndex > this.pageCount) {
        console.log('已加载完所有数据');
        return;
      }

      console.log(`获取记录列表，页码: ${this.pageIndex}`);
      this.isLoading = true;

      const { list, pageCount, success } = await creditdetal({
        credittype: this.credittype,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex
      });

      this.isLoading = false;
      this.pageCount = pageCount;

      if (this.pageIndex <= 1) {
        this.listArr = list;
      } else {
        this.listArr = [...this.listArr, ...list];
      }

      this.pageIndex++;
      uni.stopPullDownRefresh();

      console.log(`记录列表获取成功，当前页: ${this.pageIndex - 1}, 总页数: ${pageCount}`);
    }
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.reset();
  },

  onReachBottom() {
    console.log('触底加载更多');
    this.getData();
  }
};
</script>

<style lang="scss">
page {
  height: 100%;
  background: url('../../static/images/pages/farm/farmbg.png') no-repeat;
  background-size: 100% 100%;
  padding: 0rpx 0rpx;
  box-sizing: border-box;
}

.totalCount {
  height: 60rpx;
  background: rgba(34, 92, 243, 0.15);
  border-radius: 30px;
}

.rewardBox {
  background: url('../../static/images/pages/farm/block_bg.png') no-repeat;
  background-size: 100% 100%;
}

.recordBox {
  background-size: 100% 100%;
  min-height: 500rpx;
}

.reciveBtn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(0deg, #3362f9 0%, #48a2ff 100%);
  border-radius: 15rpx;
}

.animationBox {
  margin-top: 20rpx;
  background: url('../../static/images/pages/farm/bg01.png') no-repeat;
  height: 420rpx;
  background-size: 100% 100%;
}

.farmState {
  width: 159rpx;
  height: 47rpx;
  background: #277511;
  border-radius: 20rpx;
  color: #fff;
}

.btnBox {
  .recBtn {
    background: url('../../static/images/pages/farm/recBtn.png') no-repeat;
    background-size: 100% 115rpx;
    height: 115rpx;
  }
}

.imgBox {
  position: relative;

  .farmState {
    position: absolute;
    bottom: 150rpx;
    left: 50%;
    transform: translate(-50%);
  }
}
</style>